/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package ui.user.mail;

import hibernate.dao.AccountDAO;
import hibernate.dao.EntityTypeDAO;
import hibernate.entity.Accounts;
import hibernate.entity.Attachments;
import hibernate.entity.Conversations;
import hibernate.entity.Entities;
import hibernate.entity.EntityTypes;
import hibernate.entity.MessageConversations;
import hibernate.entity.MessageConversationsId;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.Date;
import java.util.Iterator;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.faces.application.FacesMessage;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.RequestScoped;
import javax.faces.bean.SessionScoped;
import javax.faces.context.FacesContext;
import javax.faces.event.ValueChangeEvent;
import javax.servlet.http.HttpSession;
//import org.apache.myfaces.custom.fileupload.UploadedFile;
import org.primefaces.event.FileUploadEvent;
import org.primefaces.model.UploadedFile;
import ui.common.AbstractUIBean;
import util.FileUpload;
//import util.UploadBean;

/**
 *
 * @author Administrator
 */
@ManagedBean
@SessionScoped
public class MailComposer extends AbstractUIBean {

    /**
     * Creates a new instance of MailComposer
     */
    String content;
    String title, receiverString;
    List<Accounts> listAccount = new ArrayList<Accounts>();
    AccountDAO accDao = new AccountDAO();
    int entityType = 1;
    FileUpload fileUpload = new FileUpload();
    String path;
    List<Attachments> listUpload;

    public MailComposer() {
        HttpSession session = getHttpSession();


    }

    public String getReceiverString() {
        return receiverString;
    }

    public void setReceiverString(String receiverString) {
        this.receiverString = receiverString;
    }

    public String getContent() {
        return content;
    }

    public void setContent(String content) {
        this.content = content;
    }
//
//    public UploadBean getUploadBean() {
//        return uploadBean;
//    }
//
//    public void setUploadBean(UploadBean uploadBean) {
//        this.uploadBean = uploadBean;
//    }
//    

    public String getTitle() {
        return title;
    }

    public void setTitle(String title) {
        this.title = title;
    }

    public List<Accounts> getListAccount() {
        return listAccount;
    }

    public void setListAccount(List<Accounts> listAccount) {
        this.listAccount = listAccount;
    }

    public void upload(FileUploadEvent event) {
        InputStream is = null;
        try {

            UploadedFile uploadFile = event.getFile();
            is = uploadFile.getInputstream();
            String absPath =uploadFile.getFileName();
           
            path = new FileUpload().processFile(uploadFile);
            System.out.println("Done!");
            FacesMessage msg = new FacesMessage("Succesful", event.getFile().getFileName() + " is uploaded.");
            FacesContext.getCurrentInstance().addMessage(null, msg);
            HttpSession session = getHttpSession();
            listUpload = (List<Attachments>) session.getAttribute("listUpload");
            if (listUpload == null) {
                listUpload = new ArrayList<Attachments>();
            }
            String fileName = absPath.substring(0, absPath.lastIndexOf("."));
            Attachments a = new Attachments(null, path, uploadFile.getFileName());
            listUpload.add(a);
            session.setAttribute("listUpload", listUpload);
        } catch (IOException ex) {
            Logger.getLogger(MailComposer.class.getName()).log(Level.SEVERE, null, ex);
        } finally {
            try {
                is.close();
            } catch (IOException ex) {
                Logger.getLogger(MailComposer.class.getName()).log(Level.SEVERE, null, ex);
            }
        }
    }

    public String send() {
        try {
            HttpSession session = getHttpSession();
            listUpload = (List<Attachments>) session.getAttribute("listUpload");

            EntityTypeDAO typeDao = new EntityTypeDAO();
            EntityTypes type = typeDao.readByID(entityType);
            Entities ent = new Entities(title, content, new Date(), new Date(), true);
            hbTransaction = hbSession.beginTransaction();
            ent.setEntityTypes(type);
            hbSession.save(ent);
            if (listUpload != null) {
                for (Attachments file : listUpload) {
                    Attachments att = file;
                    att.setEntities(ent);
                    hbSession.save(att);
                }
            }
            String[] splitReceiver = receiverString.split(";");
            for (String string : splitReceiver) {
                Accounts acc = accDao.readByEmail(string.trim());
                if (acc != null) {
                    listAccount.add(acc);
                }
            }
            for (Accounts accounts : listAccount) {
                Conversations con = new Conversations();
                hbSession.save(con);
                MessageConversations mc = new MessageConversations();
                MessageConversationsId id = new MessageConversationsId(con.getConverId(), ent.getEntityId());
                mc.setAccountsBySenderId(getCurrentAccount());
                mc.setAccountsByReceiverId(accounts);
                mc.setOrderNumber(getOrderNumber(con));
                mc.setId(id);
                mc.setReceiverStorageStatus(1);
                mc.setSenderStorageStatus(1);
                mc.setReadStatus(false);
                hbSession.update(ent);
                hbSession.update(con);
                hbSession.save(mc);

            }
            hbTransaction.commit();
        } catch (Exception e) {
            hbTransaction.rollback();
        }
        return null;

    }
}
